import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath, revalidateTag } from 'next/cache';

export async function POST(request: NextRequest) {
  try {
    // 1. 验证请求来源（防止滥用）
    const token = request.headers.get('x-revalidate-token');
    const expectedToken = process.env.REVALIDATE_TOKEN || 'your-secret-token';
    
    if (token !== expectedToken) {
      return NextResponse.json(
        { error: 'Invalid token' },
        { status: 401 }
      );
    }

    // 2. 获取请求体数据
    const body = await request.json();
    const { path, tag } = body;

    // 3. 执行重新验证
    if (path) {
      // 重新验证特定路径
      revalidatePath(path);
      console.log(`✅ 已重新验证路径: ${path}`);
    }

    if (tag) {
      // 重新验证特定标签（用于缓存标签）
      revalidateTag(tag);
      console.log(`✅ 已重新验证标签: ${tag}`);
    }

    // 4. 返回成功响应
    return NextResponse.json({
      success: true,
      message: '页面重新验证成功',
      revalidated: {
        path: path || null,
        tag: tag || null
      },
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('重新验证失败:', error);
    return NextResponse.json(
      { 
        error: '重新验证失败',
        details: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    );
  }
}

// 也支持 GET 请求（用于测试）
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const path = searchParams.get('path');
  const token = searchParams.get('token');

  try {
    // 验证token
    const expectedToken = process.env.REVALIDATE_TOKEN || 'your-secret-token';
    
    if (token !== expectedToken) {
      return NextResponse.json(
        { error: 'Invalid token' },
        { status: 401 }
      );
    }

    if (path) {
      revalidatePath(path);
      console.log(`✅ 已重新验证路径: ${path}`);
      
      return NextResponse.json({
        success: true,
        message: `路径 ${path} 重新验证成功`,
        timestamp: new Date().toISOString()
      });
    }

    return NextResponse.json({
      error: '缺少 path 参数',
      usage: 'GET /api/revalidate?path=/&token=your-secret-token'
    });

  } catch (error) {
    console.error('重新验证失败:', error);
    return NextResponse.json(
      { error: '重新验证失败' },
      { status: 500 }
    );
  }
}
